<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="150px"
    >
      <el-form-item label="客户编号/名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属行业" prop="customerIndustry">
        <el-input
          v-model="queryParams.customerIndustry"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所在省份" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入所在省份"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所在城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入所在城市"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户分类" prop="customerCategory">
       <el-select v-model="queryParams.customerCategory" clearable placeholder="请选择"  class="!w-240px">
          <el-option
            v-for="item in customerCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源" prop="customerSource">
      <el-select v-model="queryParams.customerSource" clearable placeholder="请选择"  class="!w-240px">
          <el-option
            v-for="item in customerSourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户状态" prop="customerStatus">
        <el-select v-model="queryParams.customerStatus" clearable placeholder="请选择"  class="!w-240px">
          <el-option
            v-for="item in customerStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="线索来源" prop="clueCategory">
        <el-select v-model="queryParams.clueCategory" clearable placeholder="请选择"  class="!w-240px">
          <el-option
            v-for="item in clueCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属地理区域" prop="region">
        <el-input
          v-model="queryParams.region"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:customer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:customer:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      width="100px"
    >
      <el-table-column label="客户编号" align="center" prop="id" width="200px" />
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="联系人" align="center" prop="contact" />
      <el-table-column label="手机号码" align="center" prop="mobile" />
      <el-table-column label="联系电话" align="center" prop="telephone" />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="传真" align="center" prop="fax" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="开启状态" align="center" prop="status">
        <template #default="scope">
          {{ scope.row.status === 1 ? '开启' : '关闭' }}
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="纳税人识别号" align="center" prop="taxNo" width="200px" />
      <el-table-column label="税率" align="center" prop="taxPercent" />
      <el-table-column label="开户行" align="center" prop="bankName" />
      <el-table-column label="开户账号" align="center" prop="bankAccount" />
      <el-table-column label="开户地址" align="center" prop="bankAddress" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="领用状态" align="center" prop="receivingStatus">
        <template #default="scope">
          {{ scope.row.receivingStatus === 1 ? '已领用' : '未领用' }}
        </template>
      </el-table-column>
      <el-table-column label="企业联系电话" align="center" prop="enterprisePhone" width="180px" />
      <el-table-column label="网站对外展示电话" align="center" prop="websitePhone" width="180px" />
      <el-table-column label="客户线索标签" align="center" prop="clueTags" width="150px" />
      <el-table-column label="客户所属行业" align="center" prop="customerIndustry" width="150px" />
      <el-table-column label="所在省份" align="center" prop="province" />
      <el-table-column label="所在城市" align="center" prop="city" />
      <el-table-column label="领用该客户的员工ID" align="center" prop="receiverId" width="200px" />
      <el-table-column label="分配客户的员工ID" align="center" prop="assignerId" width="200px" />
      <el-table-column
        label="客户分配时间"
        align="center"
        prop="assignmentDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="注册资金" align="center" prop="registeredCapital" />
      <el-table-column label="客户分类" align="center" prop="customerCategory" />
      <el-table-column label="客户来源渠道" align="center" prop="customerSource" width="180px" />
      <el-table-column
        label="放弃客户的原因"
        align="center"
        prop="abandonmentReason"
        width="180px"
      />
      <el-table-column label="放弃客户的员工ID" align="center" prop="abandonerId" width="200px" />
      <el-table-column label="客户状态" align="center" prop="customerStatus" />
      <el-table-column
        label="放弃客户时间"
        align="center"
        prop="abandonmentDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="公司注册地址" align="center" prop="companyAddress" width="180px" />
      <el-table-column
        label="公司法定代表人"
        align="center"
        prop="legalRepresentative"
        width="180px"
      />
      <el-table-column label="公司员工规模" align="center" prop="employeeCount" width="180px" />
      <el-table-column
        label="公司官方网站URL"
        align="center"
        prop="officialWebsite"
        width="180px"
      />
      <el-table-column label="联系人姓名" align="center" prop="contactName" width="180px" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="联系人所属部门" align="center" prop="department" width="180px" />
      <el-table-column label="联系人职务" align="center" prop="position" width="180px" />
      <el-table-column label="联系人籍贯" align="center" prop="nativePlace" width="180px" />
      <el-table-column label="其他补充说明" align="center" prop="remarks" width="180px" />
      <el-table-column label="客户跟进记录次数" align="center" prop="followUpCount" width="180px" />
      <el-table-column
        label="客户基本情况简介"
        align="center"
        prop="customerProfile"
        width="180px"
      />
      <el-table-column
        label="当前合作状态及历史记录"
        align="center"
        prop="cooperationStatus"
        width="180px"
      />
      <el-table-column label="银行开户名称" align="center" prop="bankAccountName" width="180px" />
      <el-table-column
        label="合作洽谈阶段"
        align="center"
        prop="negotiationProgress"
        width="180px"
      />
      <el-table-column label="线索来源" align="center" prop="clueCategory" width="180px" />
      <el-table-column
        label="所属二级客户ID"
        align="center"
        prop="parentCustomerId"
        width="180px"
      />
      <el-table-column label="客户等级" align="center" prop="customerLevel" />
      <el-table-column label="所属地理区域" align="center" prop="region" width="180px" />
      <el-table-column label="操作" align="center" fixed="right" width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:customer:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:customer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
import CustomerForm from './CustomerForm.vue'

/** ERP 客户 列表 */
defineOptions({ name: 'Customer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  customerIndustry: undefined,
  province: undefined,
  city: undefined,
  customerCategory: undefined,
  customerSource: undefined,
  customerStatus: undefined,
  abandonmentDate: [],
  cooperationStatus: undefined,
  clueCategory: undefined,
  region: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const customerStatusOptions = ref<{ value: string; label: string }[]>([])
const customerSourceOptions = ref<{ value: string; label: string }[]>([])
const clueCategoryOptions = ref<{ value: string; label: string }[]>([])
const customerLevelOptions = ref<{ value: string; label: string }[]>([])
const negotiationProgressOptions = ref<{ value: string; label: string }[]>([])
const customerCategoryOptions = ref<{ value: string; label: string }[]>([])

const getdictItemData = async () => {
  const data = {
    dictCode: 'customer_source'
  }
  const cusStatus = { dictCode: 'customer_status' }
  const clueCategory = { dictCode: 'clue_category' }
  const customerLevel = { dictCode: 'customer_level' }
  const negotiationProgress = { dictCode: 'negotiation_progress' }
  const customerCategory = { dictCode: 'customer_category' }

  const response = await StockApi.getByDictCode(data)
  customerSourceOptions.value = response.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const statusRes = await StockApi.getByDictCode(cusStatus)
  customerStatusOptions.value = statusRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const clueCategoryRes = await StockApi.getByDictCode(clueCategory)
  clueCategoryOptions.value = clueCategoryRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const customerLevelRes = await StockApi.getByDictCode(customerLevel)
  customerLevelOptions.value = customerLevelRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const negotiationProgressRes = await StockApi.getByDictCode(negotiationProgress)
  negotiationProgressOptions.value = negotiationProgressRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
  const customerCategoryRes = await StockApi.getByDictCode(customerCategory)
  customerCategoryOptions.value = customerCategoryRes.map((item) => ({
    value: item.id,
    label: item.description
  }))
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, 'ERP 客户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getdictItemData()
})
</script>
